// Copyright (c) 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This extension loads the saved background color for the current tab if one
// exists. The user can select a new background color from the dropdown for the
// current page, and it will be saved as part of the extension's isolated
// storage. The chrome.storage API is used for this purpose. This is different
// from the window.localStorage API, which is synchronous and stores data bound
// to a document's origin. Also, using chrome.storage.sync instead of
// chrome.storage.local allows the extension data to be synced across multiple
// user devices.
//'use strict';

function addNode(tick,data)
{
    data.forEach((v,i)=>{
        if(Array.isArray(v)){
            let numtd = document.createElement('td');
            let numtr = document.createElement('tr');
            let numimages = document.createElement('num-image');
            numimages.setAttribute('data',JSON.stringify(v));
            numtd.appendChild(numimages);
            numtr.appendChild(numtd);
            document.querySelector('#data tbody').appendChild(numtr);
        }
        else{
            let title = document.createElement('tr');
            let titlesz = document.createElement('span');
            if(i==0){
                let titlehead = document.createElement('span');
                titlehead.textContent = tick;
                titlehead.style.fontSize = '18px';
                titlehead.style.color = 'red';
                title.appendChild(titlehead);
            }
            titlesz.textContent = v;
            titlesz.style.fontSize = '12px';
            title.appendChild(titlesz);
            if(i==data.length-1){
                title.style.borderBottom = '2px solid blue';
            }
            document.querySelector('#data tbody').appendChild(title);
        }
    });
}

let dataQuery=null;
try{
    let work = chrome.extension.getBackgroundPage();
    dataQuery = work.query();
}
catch(e)
{
    dataQuery = work.query();
}
finally{
    if(dataQuery.length>0){
        dataQuery.forEach((o)=>{
            o.then(res=>{
                if(res.size>0)
                res.forEach((v,k)=>{
                    addNode(k,v);
                })
            })
        });
    }
}